<template>
    <div>
        <Breadcrumb :style="{margin: '20px 0'}">
            <BreadcrumbItem>发布操作</BreadcrumbItem>
            <BreadcrumbItem>图片发布</BreadcrumbItem>
        </Breadcrumb>
        <ButtonGroup class="button">
            <Button type="primary" @click="reload">刷新</Button>
            <Button type="primary" @click="batchPush">批量发布</Button>
        </ButtonGroup>
        <Table :columns="columns" :data="deviceList"></Table>
        <Modal
            v-model="fileListModel"
            title="文件列表">
            <template v-for="(value,index) in fileList">
                <div :key="value" class="item-list" @click="selectDirectionPath(index,type)">{{ value }}</div>
            </template>
        </Modal>
    </div>
</template>

<script>
import model from '../util/model'
import {ipcRenderer} from 'electron'
import fs from 'fs'
import process from 'child_process'

export default {
    name: 'PullPicture',
    data: function () {
        return {
            deviceList: [],
            getPath: null,
            activeTableIndex:0,
            columns: [
                {
                    title: '名称',
                    key: 'name'
                },
                {
                    title: '设备号',
                    key: 'device'
                },
                {
                    title: '图片地址',
                    render: (h, params) => {
                        return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'default',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.setPicturePath(params.index)
                                        }
                                    }
                                }, params.row.pic ? params.row.pic : '设置')
                            ]
                        )
                    }
                },
                {
                    title: '图片文件',
                    render: (h, params) => {
                        return h('div', [
                            h('span', {
                                style: {
                                    'padding-right': '10px'
                                }
                            }, params.row.pictureDirectory),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.addPicture(params.index)
                                    }
                                }
                            }, params.row.pictureDirectory ? '修改' : '设置')
                        ])
                    }
                },
                {
                    title: '操作',
                    render: (h, p) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.pushPicture(p)
                                    }
                                }
                            }, '发布')
                        ])
                    }
                }
            ],
            scanDevice: [],
            fileListModel:false,
            fileList:[]
        }
    },
    created: function () {
        this.getDeviceList()
    },
    methods: {
        reload: function () {
            this.getDeviceList()
        },
        getDeviceList: function () {
            let that = this
            let newStdout = []
            let deviceArr = []
            let valueTemp = ''
            let valueTemp2 = ''
            let deviceNumberArr = []
            let item = {
                index: '',
                device: ''
            }
            process.exec('adb devices', {timeout: 10000}, function (error, stdout, stderr) {
                if (stdout) {
                    newStdout = stdout.split('\n')
                    deviceArr = newStdout.slice(1, -1)
                    if (deviceArr.length > 0) {
                        let testValue = deviceArr[0].replace(/[\r\n]*/g, '')
                        if (testValue !== '') {
                            deviceArr.forEach((value, index) => {
                                valueTemp2 = value.replace(/[\r\n]*/g, '')
                                if (valueTemp2 !== '') {
                                    valueTemp = valueTemp2.split('\t')
                                    item = {}
                                    item.device = valueTemp[0]
                                    deviceNumberArr[index] = item
                                }
                            })
                        } else {
                            that.$Message.info('没有找到设备')
                            return
                        }
                        model.info.find({$or: deviceNumberArr}, function (err, doc) {
                            console.log(doc)
                            if (doc) {
                                that.deviceList = doc
                            }
                        })
                    } else {
                        that.$Message.info('没有找到设备')
                    }
                } else {
                    that.$Message.info('没有找到设备')
                }
            })
        },
        setPicturePath: function (index) {
            // if(this.isLinking[index]){
            let that = this
            this.type = 1
            let command = 'adb -s '
            let device = this.deviceList[index].device
            this.activeTableIndex = index
            let directList = []
            command = command + device + ' shell ls -l /storage/emulated/0'
            console.log(command)
            process.exec(command, {timeout:3000},(error, stdout, stderr) => {
                if (stdout) {
                    let arr = stdout.split('\n')
                    let arr2 = arr.slice(1, -1)
                    if (arr2.length > 0) {
                        arr2.forEach((value, index) => {
                            if (value[0] === 'd') {
                                let temp = value.split(' ')
                                directList.push(temp[temp.length - 1])
                                that.fileList = directList
                                that.fileListModel = true
                            }
                        })
                    }
                }
            })
            // }
        },
        selectDirectionPath: function (index, type) {
            let that = this
            let directionPath = '/storage/emulated/0/' + this.fileList[index]
            let device = this.deviceList[this.activeTableIndex].device
            model.info.update({device: device}, {$set: {pic: directionPath}}, {multi: true}, function (err, newDoc) {
                if (newDoc) {
                    that.$Message.info('设置成功')
                    // that.dataList[that.activeTableIndex].pic = directionPath
                    that.$set(that.deviceList[that.activeTableIndex], 'pic', directionPath)
                    that.fileListModel = false
                }
            })
            // } else {
            //     model.info.update({device: device}, {$set: {radio: directionPath}}, {multi: true}, function (err, newDoc) {
            //         if (newDoc) {
            //             that.$Message.info('设置成功')
            //             that.$set(that.dataList[that.activeTableIndex],'radio',directionPath)
            //             that.fileListModel = false
            //         }
            //     })
            // }
        },
        addPicture: function (index) {
            // ipcRenderer.send('open-directory-dialog','openDirectory');
            let that = this
            let id = this.deviceList[index]._id
            console.log(this.deviceList)
            ipcRenderer.send('open-directory-dialog-2', 'openDirectory')
            ipcRenderer.on('selectedItem', (event, directionPath) => {
                //console.log(directionPath)
                if (directionPath) {
                    model.info.update({_id: id}, {$set: {pictureDirectory: directionPath}}, (error, rows) => {
                        if (rows) {
                            that.$Message.info('设置成功')
                            that.getDeviceList()
                        }
                    })
                }
            })
        },
        pushPicture: function (p) {
            let path = p.row.pictureDirectory
            let that = this
            let filePath = ''
            let command = 'adb -s '
            let lastCommand = ''
            if(parseInt(p.row.isReal)){
                command = command +  p.row.ip + ':' + p.row.port + ' push '
            }else{
                command = command +  p.row.device + ' push '
            }

            fs.readdir(path, (err, files) => {
                if (err) {
                    that.$Message.info('文件夹不存在')
                    return
                }
                console.log(files)
                files.forEach((file, index) => {
                    filePath = path + '\\' + file
                    lastCommand = command + filePath + ' ' + p.row.pic
                    process.exec(lastCommand, (error, stdout) => {
                        if(error){
                            return
                        }else{
                            that.$Message.info(发布成功)
                        }
                    })
                })
            })
        },
        batchPush: function () {

        }
    }
}
</script>

<style scoped>
.item-list {
    padding: 3px;
    border-bottom: 1px solid #8ebbe8;
    cursor: pointer;
}

.item-list:hover {
    background-color: #b4b4f3;
}
</style>
